﻿Imports System.Xml.Serialization

Public MustInherit Class DefaultConfig
    Inherits ClsBase

    REM 文件所在路径变量
    Private Shared mConfigFilePath As String
    Private Shared mConfigInfo As IConfigInfo
    Private Shared mlockHelper As New Object()

    REM 文件所在路径
    Private Shared Property ConfigFilePath() As String
        Get
            Return mConfigFilePath
        End Get
        Set(ByVal value As String)
            mConfigFilePath = value
        End Set
    End Property

    REM XML反序列
    Protected Shared Function DeserializeInfo(ByVal configfilepath As String, ByVal configtype As Type) As IConfigInfo
        Return CType(Serialization.Load(configtype, configfilepath), IConfigInfo)
    End Function

    REM 读取序列
    Protected Shared Function LoadConfig(ByRef fileoldchange As DateTime, ByVal configFilePath As String, ByVal configinfo As IConfigInfo) As IConfigInfo
        Return LoadConfig(fileoldchange, configFilePath, configinfo, True)
    End Function

    Protected Shared Function LoadConfig(ByRef fileoldchange As DateTime, ByVal configFilePath As String, ByVal configinfo As IConfigInfo, ByVal checkTime As Boolean) As IConfigInfo
        mConfigFilePath = configFilePath
        mConfigInfo = configinfo
        If checkTime Then
            Dim m_filenewchange As DateTime = System.IO.File.GetLastWriteTime(configFilePath)
            REM 当程序运行中config文件发生变化时则对config重新赋值
            If (fileoldchange <> m_filenewchange) Then
                fileoldchange = m_filenewchange

                SyncLock mlockHelper
                    mConfigInfo = DeserializeInfo(configFilePath, configinfo.GetType)
                End SyncLock

            End If
        Else
            SyncLock mlockHelper
                mConfigInfo = DeserializeInfo(configFilePath, configinfo.GetType)
            End SyncLock
        End If
        Return mConfigInfo
    End Function

    Protected Shared Function SaveConfig() As Boolean
        Return SaveConfig(mConfigFilePath, mConfigInfo)
    End Function

    Protected Shared Function SaveConfig(ByVal configFilePath As String, ByVal configinfo As IConfigInfo) As Boolean
        Return Serialization.Save(configinfo, configFilePath)
    End Function

    Protected Overrides Sub Finalize()
        mConfigInfo = Nothing
        MyBase.Finalize()
    End Sub

End Class

Public Interface IConfigInfo

End Interface